import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import LunaServer.core.LunaServer;
import LunaServer.routing.Route;

/**
 * 登出路由处理器
 * 处理/logout路径的请求
 */
public class LogoutRoute implements Route {

    private final LunaServer server;

    public LogoutRoute(LunaServer server) {
        this.server = server;
    }

    /**
     * 处理HTTP请求
     * 
     * @param exchange HttpExchange对象
     * @return 响应内容
     */
    public String handleRequest(HttpExchange exchange) throws IOException {
        String response = "";
        int responseCode = 200;
        
        try {
            // 读取请求体
            String requestBody = "";
            try (InputStream is = exchange.getRequestBody()) {
                requestBody = new String(is.readAllBytes(), StandardCharsets.UTF_8);
            }
            
            // 解析请求数据
            Gson gson = new Gson();
            Map<String, String> requestData = gson.fromJson(requestBody, Map.class);
            
            String token = requestData.get("token");
            
            // 使token失效
            invalidateToken(token);
            
            // 构造响应
            Map<String, Object> result = new HashMap<>();
            result.put("code", "200");
            result.put("time", Instant.now().toString());
            response = gson.toJson(result);
            
            // 设置响应头
            exchange.getResponseHeaders().set("Content-Type", "application/json");
        } catch (Exception e) {
            responseCode = 400;
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", "400");
            errorResult.put("error", "Invalid JSON format");
            errorResult.put("time", Instant.now().toString());
            Gson gson = new Gson();
            response = gson.toJson(errorResult);
            exchange.getResponseHeaders().set("Content-Type", "application/json");
        }
        
        // 发送响应
        exchange.sendResponseHeaders(responseCode, response.getBytes(StandardCharsets.UTF_8).length);
        return response;
    }
    
    /**
     * 使token失效
     * 
     * @param token 用户token
     */
    private void invalidateToken(String token) {
        // 简单示例：实际应该在数据库或缓存中删除token或标记为失效
        if (token != null && token.startsWith("token_for_")) {
            String username = token.replace("token_for_", "");
            
            // 从LunaServer实例获取数据库连接参数
            String dbUrl = server.getDbUrl();
            String dbUser = server.getDbUser();
            String dbPass = server.getDbPass();

            // 示例：更新用户最后登出时间（实际应该有专门的token表）
            String sql = "UPDATE users SET last_logout = NOW() WHERE username = ?";

            try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);
                 PreparedStatement pstmt = conn.prepareStatement(sql)) {

                pstmt.setString(1, username);
                pstmt.executeUpdate();

            } catch (SQLException e) {
                System.err.println("Database error during token invalidation: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}